import config from 'config';

import { ObjectStorage } from './objectStorage';
import { MinioConfig, MinioStorage } from './minioStorage';
import {OssConfig, OssStorage} from "$infra/storage/ossStorage";
export interface ObjectStorageOption {
  type: string,
  config: any
}

function getStorageFactory(options?: ObjectStorageOption): ObjectStorage {
  if (options) {
    if (options.type === 'minio') {
      const miniConfig = options.config as MinioConfig;
      return new MinioStorage(miniConfig);
    } else if (options.type === 'oss') {
      const ossConfig = options.config as OssConfig;
      return new OssStorage(ossConfig);
    }
    throw new Error(`unsupported object storage backend ${options.type}`);
  } else {
    const type = config.get('storage.type');
    if (type === 'minio') {
      const minioConfig: MinioConfig = {
        host: config.get<string>('storage.minio.host'),
        port: config.get<number>('storage.minio.port'),
        useSSL: config.has('storage.minio.useSSL') ? config.get<boolean>('storage.minio.useSSL') : false,
        accessKey: config.get<string>('storage.minio.accessKey'),
        accessSecret: config.get<string>('storage.minio.accessSecret')
      };
      return new MinioStorage(minioConfig);
    } 
    throw new Error(`unsupported object storage backend ${type}`);
  }
}
export class Storage {

  private static _instance: ObjectStorage;
  private constructor() { }

  public static initialize(options: ObjectStorageOption): ObjectStorage {
    if (!this._instance) {
      this._instance = getStorageFactory(options);
    }
    return this._instance;
  }

  public static get Instance() {
    return this._instance;
  }
}